package com.example.cos;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.endpoint.EndpointBuilder;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.region.Region;

import java.io.InputStream;

import static com.example.cos.COSUtil.cos_region;

public class COSUtil {

    private static COSClient cosClient = null;

    private static String secretId = "ANr9rRGBRULL/2G0etCH";
    private static String secretKey = "rfcnQJYJ6iWl1UyqVquFcEJXvypi89escfAW7EWR";
    public  static final String cos_region = "http://172.19.128.7:5246";

    private static String cosBucketName = "test3";

    public static void main(String[] args) {
        InputStream is = null;
        String filePath = "test.txt";
        try {
            COSClient client = getCosClient();
            COSObject cosObject = client.getObject(cosBucketName, filePath);
            is = cosObject.getObjectContent();
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

    public static COSClient getCosClient() {
        if (cosClient == null) {

            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            ClientConfig clientConfig = new ClientConfig(new Region(cos_region));
            clientConfig.setSocketTimeout(30 * 1000);
            clientConfig.setHttpProtocol(HttpProtocol.http);
            SelfDefinedEndpointBuilder selfDefinedEndpointBuilder = new SelfDefinedEndpointBuilder();
            clientConfig.setEndpointBuilder(selfDefinedEndpointBuilder);
            cosClient = new COSClient(cred, clientConfig);
        }
        return cosClient;
    }
}


class SelfDefinedEndpointBuilder implements EndpointBuilder {
    @Override
    public String buildGeneralApiEndpoint(String bucketName) {
        return String.format("%s.%s", bucketName,cos_region);
    }

    @Override
    public String buildGetServiceApiEndpoint() {
        return cos_region;
    }
}